package com.smartcampusbackend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.SystemLogService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import com.smartcampusbackend.util.FileUploadUtil;
import com.smartcampusbackend.util.PermissionUtil;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @GetMapping
    public List<User> listUsers() {
        return userService.list();
    }

    /**
     * 获取指定角色的所有用户
     * @param role 角色名称
     * @return 用户列表
     */
    @GetMapping("/by-role")
    public ResponseEntity<List<User>> getUsersByRole(@RequestParam String role) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role", role);
            List<User> users = userService.list(queryWrapper);
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping
    public void addUser(@RequestBody User user) {
        userService.save(user);
    }

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SystemLogService systemLogService;

    /**
     * 获取当前登录用户信息（用于权限刷新）
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentUserInfo(HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            // 构建用户信息响应
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", currentUser.getId());
            userInfo.put("username", currentUser.getUsername());
            userInfo.put("name", currentUser.getRealName());
            userInfo.put("role", currentUser.getRole());
            userInfo.put("avatar", currentUser.getAvatar());
            userInfo.put("email", currentUser.getEmail());
            userInfo.put("phone", currentUser.getPhone());
            userInfo.put("department", currentUser.getDepartment());
            userInfo.put("major", currentUser.getMajor());
            userInfo.put("grade", currentUser.getGrade());
            userInfo.put("className", currentUser.getClassName());
            userInfo.put("studentId", currentUser.getStudentId());
            userInfo.put("teacherId", currentUser.getTeacherId());
            userInfo.put("title", currentUser.getTitle());
            userInfo.put("subject", currentUser.getSubject());
            userInfo.put("status", currentUser.getStatus());
            userInfo.put("createTime", currentUser.getCreateTime());
            userInfo.put("updateTime", currentUser.getUpdateTime());
            userInfo.put("lastLogin", currentUser.getLastLogin());

            // 根据角色生成权限列表
            List<String> permissions = generatePermissions(currentUser.getRole());
            userInfo.put("permissions", permissions);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取用户信息成功");
            result.put("data", userInfo);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "获取用户信息失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户角色生成权限列表
     */
    private List<String> generatePermissions(String role) {
        List<String> permissions = new ArrayList<>();

        // 基础权限
        permissions.add("view_notice");
        permissions.add("view_services");
        permissions.add("view_download");
        permissions.add("view_guide");

        switch (role) {
            case "ADMIN":
                permissions.add("user_manage");
                permissions.add("system_config");
                permissions.add("data_analysis");
                permissions.add("log_audit");
                permissions.add("notice_manage");
                permissions.add("system_monitor");
                permissions.add("user_import");
                permissions.add("user_delete");
                permissions.add("user_create");
                permissions.add("user_update");
                permissions.add("user_stats");
                permissions.add("password_reset");
                break;
            case "TEACHER":
                permissions.add("user_view");
                permissions.add("user_stats");
                permissions.add("student_manage");
                break;
            case "STUDENT":
                permissions.add("profile_edit");
                permissions.add("course_select");
                permissions.add("grade_view");
                break;
            case "STAFF":
                permissions.add("service_manage");
                permissions.add("maintenance");
                break;
        }

        return permissions;
    }

    /**
     * 获取当前登录用户信息
     */
    private User getCurrentUser(HttpServletRequest request) {
        // 从请求头获取token，这里简化处理，实际应该从JWT中解析
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 这里应该根据token获取用户信息，暂时返回模拟数据
            System.out.println("Extracted token: " + token);
            String username = tokenService.getUsernameByToken(token);
            System.out.println("Username from token: " + username);
            if(username != null)
            {
                User user= userService.getByUsername(username);
                System.out.println("currentUser="+user);
                if (user == null) {
                    System.out.println("Token 解析成功但用户不存在: " + username);
                }
                return user;
            }else {
                System.out.println("Token 无法找到对应的用户名");
            }
        } else {
            System.out.println("Authorization header 缺失或格式不对");
        }
        return null;
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }

    @PutMapping("/update")
    public Map<String, Object> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        try {
            log.info("Received update request for user ID: {}", user.getId());
            log.info("User data: {}", user);

            // 获取当前用户和客户端信息
            User currentUser = getCurrentUser(request);
            String ipAddress = getClientIpAddress(request);
            String userAgent = request.getHeader("User-Agent");

            // 验证用户ID
            if (user.getId() == null) {
                log.error("User ID is null");
                response.put("code", 400);
                response.put("message", "用户ID不能为空");
                response.put("data", null);
                return response;
            }

            // 确保ID是有效的数字
            Integer userId;
            try {
                userId = Integer.valueOf(user.getId().toString());
                log.info("Parsed user ID: {}", userId);
            } catch (NumberFormatException e) {
                log.error("Invalid user ID format: {}", user.getId());
                response.put("code", 400);
                response.put("message", "用户ID格式无效: " + user.getId());
                response.put("data", null);
                return response;
            }

            // 检查用户是否存在
            User existingUser = userService.getById(userId);
            if (existingUser == null) {
                log.error("User not found with ID: {}", userId);
                response.put("code", 404);
                response.put("message", "用户不存在，ID: " + userId);
                response.put("data", null);
                return response;
            }

            log.info("Found existing user: {}", existingUser.getRealName());

            // 处理唯一索引字段的空值问题
            if (user.getStudentId() != null && user.getStudentId().trim().isEmpty()) {
                log.info("Converting empty studentId to null");
                user.setStudentId(null);
            }
            if (user.getTeacherId() != null && user.getTeacherId().trim().isEmpty()) {
                log.info("Converting empty teacherId to null");
                user.setTeacherId(null);
            }
            if (user.getIdNumber() != null && user.getIdNumber().trim().isEmpty()) {
                log.info("Converting empty idNumber to null");
                user.setIdNumber(null);
            }
            if (user.getPhone() != null && user.getPhone().trim().isEmpty()) {
                log.info("Converting empty phone to null");
                user.setPhone(null);
            }
            if (user.getEmail() != null && user.getEmail().trim().isEmpty()) {
                log.info("Converting empty email to null");
                user.setEmail(null);
            }

            // 更新用户信息
            user.setId(userId);
            boolean updated = userService.updateById(user);

            if (updated) {
                log.info("Successfully updated user with ID: {}", userId);

                // 记录操作日志
                if (currentUser != null) {
                    systemLogService.logOperation(
                            currentUser.getUsername(),
                            currentUser.getId(),
                            "修改个人信息",
                            "用户更新个人信息",
                            ipAddress,
                            userAgent,
                            request.getRequestURL().toString(),
                            request.getMethod(),
                            null,
                            200,
                            null,
                            "SUCCESS"
                    );
                }

                response.put("code", 200);
                response.put("message", "用户信息更新成功");
                response.put("data", userService.getById(userId));
                return response;
            } else {
                log.error("Failed to update user with ID: {}", userId);

                // 记录操作失败日志
                if (currentUser != null) {
                    systemLogService.logOperation(
                            currentUser.getUsername(),
                            currentUser.getId(),
                            "修改个人信息",
                            "用户更新个人信息失败",
                            ipAddress,
                            userAgent,
                            request.getRequestURL().toString(),
                            request.getMethod(),
                            null,
                            400,
                            null,
                            "FAILED"
                    );
                }

                response.put("code", 400);
                response.put("message", "更新失败");
                response.put("data", null);
                return response;
            }

        } catch (Exception e) {
            log.error("Error updating user info", e);
            response.put("code", 500);
            response.put("message", "服务器内部错误: " + e.getMessage());
            response.put("data", null);
            return response;
        }
    }

    @PostMapping("/avatar")
    public Map<String, Object> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                Map<String, Object> resp = new HashMap<>();
                resp.put("code", 401);
                resp.put("message", "未登录");
                resp.put("data", null);
                return resp;
            }

            // 验证文件
            if (!FileUploadUtil.isValidImage(file)) {
                Map<String, Object> resp = new HashMap<>();
                resp.put("code", 400);
                resp.put("message", "请上传有效的图片文件（JPG、PNG、GIF）");
                resp.put("data", null);
                return resp;
            }

            // 上传文件
            String avatarUrl = FileUploadUtil.uploadAvatar(file);

            // 获取当前用户信息
            User user = userService.getById(currentUser.getId());
            if (user == null) {
                Map<String, Object> resp = new HashMap<>();
                resp.put("code", 404);
                resp.put("message", "用户不存在");
                resp.put("data", null);
                return resp;
            }

            // 删除旧头像文件
            if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                FileUploadUtil.deleteAvatar(user.getAvatar());
            }

            // 更新用户头像路径
            user.setAvatar(avatarUrl);
            userService.updateById(user);

            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 200);
            resp.put("message", "头像上传成功");
            Map<String, String> data = new HashMap<>();
            data.put("url", avatarUrl);
            resp.put("data", data);

            return resp;
        } catch (IllegalArgumentException e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 400);
            resp.put("message", e.getMessage());
            resp.put("data", null);
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 500);
            resp.put("message", "头像上传失败: " + e.getMessage());
            resp.put("data", null);
            return resp;
        }
    }

    // 分页+搜索用户（需要管理员或教师权限）
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> pageUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Integer status,
            HttpServletRequest request
    ) {
        try {
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            // 检查权限
            if (!PermissionUtil.canViewUserList(currentUser)) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }

            IPage<User> userPage = userService.pageUsers(page, size, username, role, status);

            // 过滤敏感信息
            List<User> filteredUsers = userPage.getRecords().stream()
                    .map(user -> PermissionUtil.filterUserInfo(currentUser, user))
                    .collect(Collectors.toList());

            userPage.setRecords(filteredUsers);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("data", userPage);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", e.getMessage()));
        }
    }

    // 批量导入用户（仅管理员）
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importUsers(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request
    ) {
        try {
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            // 检查权限
            if (!PermissionUtil.canCreateUser(currentUser)) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }

            Map<String, Object> result = userService.importUsersFromExcel(file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", e.getMessage()));
        }
    }
    // 新增用户（仅管理员）
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createUser(
            @RequestBody User user,
            HttpServletRequest request
    ) {
        try {
            // 空字符串转为null，防止唯一索引冲突
            if ("".equals(user.getIdNumber())) user.setIdNumber(null);
            if ("".equals(user.getPhone())) user.setPhone(null);
            if ("".equals(user.getEmail())) user.setEmail(null);
            if ("".equals(user.getStudentId())) user.setStudentId(null);
            if ("".equals(user.getTeacherId())) user.setTeacherId(null);

            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            // 检查权限
            if (!PermissionUtil.canCreateUser(currentUser)) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }

            userService.register(user);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "用户创建成功");
            return ResponseEntity.ok(result);
        } catch (RuntimeException e) {
            // 处理业务逻辑错误（如用户名已存在、邮箱已注册等）
            log.error("创建用户失败: {}", e.getMessage());
            return ResponseEntity.status(400).body(Map.of("code", 400, "message", e.getMessage()));
        } catch (Exception e) {
            // 处理其他系统错误
            log.error("创建用户时发生系统错误", e);
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", "系统错误: " + e.getMessage()));
        }
    }

    // 删除用户（仅管理员，且不能删除自己或其他管理员）
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @PathVariable Integer id,
            HttpServletRequest request
    ) {
        try {
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            User targetUser = userService.getById(id);
            if (targetUser == null) {
                return ResponseEntity.status(404).body(Map.of("code", 404, "message", "用户不存在"));
            }

            // 检查权限
            if (!PermissionUtil.canDeleteUser(currentUser, targetUser)) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }

            userService.removeById(id);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "用户删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("code", 500, "message", e.getMessage()));
        }
    }
    // 管理员更新用户信息
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> adminUpdateUser(
            @PathVariable Integer id,
            @RequestBody User user,
            HttpServletRequest request
    ) {
        try {
            // 空字符串转为null，防止唯一索引冲突
            if ("".equals(user.getIdNumber())) user.setIdNumber(null);
            if ("".equals(user.getPhone())) user.setPhone(null);
            if ("".equals(user.getEmail())) user.setEmail(null);
            if ("".equals(user.getStudentId())) user.setStudentId(null);
            if ("".equals(user.getTeacherId())) user.setTeacherId(null);
            User currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return ResponseEntity.status(401).body(Map.of("code", 401, "message", "未登录"));
            }

            // 检查权限
            if (!PermissionUtil.canCreateUser(currentUser)) {
                return ResponseEntity.status(403).body(Map.of("code", 403, "message", "权限不足"));
            }

            User existingUser = userService.getById(id);
            if (existingUser == null) {
                return ResponseEntity.status(404).body(Map.of("code", 404, "message", "用户不存在"));
            }

            // 管理员可以修改所有字段（包括role、studentId、teacherId），但保护系统字段
            user.setId(id);
            user.setCreateTime(existingUser.getCreateTime());
            user.setPassword(existingUser.getPassword());
            userService.updateById(user);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "用户更新成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(400).body(Map.of("code", 400, "message", e.getMessage()));
        }
    }
}